package Socketserver.SQL;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ForMysql {
    String Driver;
    String url;
    String Username;
    String Password;
    String DATABASE_name;
    String TABLE_NAME_USR;
    String TABLE_NAME_TXT;

    /**
     * mysql_java_class(处理数据操作 的输入输出)
     */
    public ForMysql(
            Boolean iT_CAN_MOVE_OR_NOT,
            String Driver,
            String url,
            String Username,
            String getPassword,
            String DATABASE_NAME,
            String TABLE_NAME_USR,
            String TABLE_NAME_TXT
    ) {
        if (iT_CAN_MOVE_OR_NOT != false) {
            try {
                Class.forName(Driver);
                try {
                    Connection connction = DriverManager.getConnection(
                            url,
                            Username,
                            getPassword
                    );
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                this.Driver = Driver;
                this.url = url;
                this.Username = Username;
                this.Password = getPassword;
                this.DATABASE_name = DATABASE_NAME;
                this.TABLE_NAME_USR = TABLE_NAME_USR;
                this.TABLE_NAME_TXT = TABLE_NAME_TXT;
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }

    /**
     * 关闭资源工具方法
     */
    private void closeResources(Connection conn, PreparedStatement ps, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (ps != null) ps.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            System.out.println("资源关闭异常：" + e.getMessage());
        }
    }

    /**
     * 参数化执行SQL（支持增删改）
     * @param sql SQL语句（使用?占位符）
     * @param params 参数数组
     * @return 执行结果
     */
    private boolean executeUpdateWithParams(String sql, Object[] params) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            Class.forName(Driver);
            conn = DriverManager.getConnection(url, Username, Password);
            // 切换数据库
            ps = conn.prepareStatement("USE " + DATABASE_name);
            ps.execute();

            // 执行带参数的SQL
            ps = conn.prepareStatement(sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]); // 占位符索引从1开始
                }
            }
            ps.executeUpdate();
            return true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return false;
        } finally {
            closeResources(conn, ps, null);
        }
    }

    /**
     * 单表添加 - 用户表
     * 用户表格式：id, name, password, type, is_root
     */
    public boolean INSERT_INTO_TABLE_User(
            String id,
            String name,
            String password,
            String type,
            int isRoot
    ) {
        // 使用参数化查询，避免单引号拼接错误
        String sql = "INSERT INTO " + TABLE_NAME_USR +
                " (id, name, password, type, is_root) " +
                "VALUES (?, ?, ?, ?, ?)";
        Object[] params = {
                id.replace("'", ""),  // 移除可能的多余单引号
                name.replace("'", ""),
                password.replace("'", ""),
                type.replace("'", ""),
                isRoot
        };
        return executeUpdateWithParams(sql, params);
    }

    /**
     * 指定删除 - 用户表
     */
    public boolean DELETE_TABLE_User_What(
            String what,
            String equals_what
    ) {
        String sql;
        Object[] params;
        if (!what.isEmpty()) {
            sql = "DELETE FROM " + TABLE_NAME_USR + " WHERE " + what + " LIKE ?";
            params = new Object[]{equals_what};
        } else {
            sql = "DELETE FROM " + TABLE_NAME_USR;
            params = null;
        }
        return executeUpdateWithParams(sql, params);
    }

    /**
     * 修改 - 用户表（增加id筛选，确保操作精准性）
     */
    public boolean ALTER_TABLE_User_What(
            String id,  // 新增：要修改的用户id
            String what, // 要修改的字段名
            String equals_what, // 该字段的旧值（用于匹配）
            String chang_data // 要修改的新值
    ) {
        // 校验必要参数，id和修改字段均不能为空
        if (id == null || id.isEmpty() || what.isEmpty()) {
            return false;
        }
        // 参数化修改语句，增加id筛选条件
        String sql = "UPDATE " + TABLE_NAME_USR +
                " SET " + what + " = ? " +
                " WHERE id = ? AND " + what + " LIKE ?";  // 同时通过id和字段旧值筛选
        Object[] params = {
                chang_data.replace("'", ""),  // 新值
                id.replace("'", ""),          // 要修改的用户id（精确匹配）
                "%" + equals_what + "%"       // 字段旧值（模糊匹配）
        };
        return executeUpdateWithParams(sql, params);
    }

    /**
     * 单表添加 - TXT表
     * TXT表格式：TXT_id, TXT_name, TXT_address, TXT_author
     */
    public boolean INSERT_INTO_TABLE_txt(
            String id,
            String name,
            String address,
            String author
    ) {
        // 参数化插入
        String sql = "INSERT INTO " + TABLE_NAME_TXT +
                " (TXT_id, TXT_name, TXT_address, TXT_author) " +
                "VALUES (?, ?, ?, ?)";
        Object[] params = {
                id.replace("'", ""),
                name.replace("'", ""),
                address.replace("'", ""),
                author.replace("'", "")
        };
        return executeUpdateWithParams(sql, params);
    }

    /**
     * 指定删除 - TXT表
     */
    public boolean DELETE_TABLE_txt_What(
            String what,
            String equals_what,
            String author
    ) {
        if (!author.equals("root")) {
            return false;
        }
        String sql;
        Object[] params;
        if (!what.isEmpty()) {
            sql = "DELETE FROM " + TABLE_NAME_TXT +
                    " WHERE " + what + " LIKE ? AND TXT_author = ?";
            params = new Object[]{equals_what, author};
        } else {
            sql = "DELETE FROM " + TABLE_NAME_TXT;
            params = null;
        }
        return executeUpdateWithParams(sql, params);
    }

    /**
     * 修改 - TXT表
     */
    public boolean ALTER_TABLE_txt_What(
            String what,
            String equals_what,
            String chang_data
    ) {
        if (what.isEmpty()) {
            return false;
        }
        // 参数化修改
        String sql = "UPDATE " + TABLE_NAME_TXT +
                " SET " + what + " = ? " +
                " WHERE " + what + " LIKE ?";
        Object[] params = {
                chang_data.replace("'", ""),
                equals_what
        };
        return executeUpdateWithParams(sql, params);
    }

    /**
     * 通用查询模板（参数化）
     */
    private List<Map<String, String>> queryWithParams(String sql, Object[] params, String HOW) {
        List<Map<String, String>> resultList = new ArrayList<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            Class.forName(Driver);
            conn = DriverManager.getConnection(url, Username, Password);
            // 切换数据库
            ps = conn.prepareStatement("USE " + DATABASE_name);
            ps.execute();

            // 执行查询
            ps = conn.prepareStatement(sql);
            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }
            }
            rs = ps.executeQuery();

            // 处理结果集
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            boolean hasData = false;

            while (rs.next()) {
                hasData = true;
                Map<String, String> rowData = new HashMap<>();
                for (int i = 1; i <= columnCount; i++) {
                    String colName = metaData.getColumnName(i);
                    rowData.put(colName, rs.getString(i));
                }
                resultList.add(rowData);
            }
            if (!hasData) {
                System.out.println("查询结果集为空");
            }
        } catch (Exception e) {
            System.out.println("查询异常：" + e.getMessage());
        } finally {
            closeResources(conn, ps, rs);
        }
        return resultList;
    }

    /**
     * 用户表查询
     */
    public List<Map<String, String>> SELECT_FROM_FIND_MY_Account(String value, String HOW) {
        String sql;
        Object[] params;
        if (value == null || value.isEmpty()) {
            sql = "SELECT * FROM " + TABLE_NAME_USR;
            params = null;
        } else if (HOW.equals("id")) {
            sql = "SELECT * FROM " + TABLE_NAME_USR + " WHERE " + HOW + " = ?";
            params = new Object[]{value};
        } else {
            sql = "SELECT * FROM " + TABLE_NAME_USR + " WHERE " + HOW + " LIKE ?";
            params = new Object[]{"%" + value + "%"};
        }
        List<Map<String, String>> originalResult = queryWithParams(sql, params, HOW);

        // 隐藏敏感信息
        List<Map<String, String>> filteredResult = new ArrayList<>();
        for (Map<String, String> row : originalResult) {
            Map<String, String> filteredRow = new HashMap<>(row);
//            if (filteredRow.containsKey("id")) {
//                filteredRow.put("id", "***");
//            }
            filteredResult.add(filteredRow);
        }
        return filteredResult;
    }

    /**
     * TXT表查询
     */
    public List<Map<String, String>> SELECT_FROM_FIND_MY_TXT(String value, String HOW) {
        String sql;
        Object[] params;
        if (value == null || value.isEmpty()) {
            sql = "SELECT * FROM " + TABLE_NAME_TXT;
            params = null;
        } else if (HOW.equals("TXT_id")) {
            sql = "SELECT * FROM " + TABLE_NAME_TXT + " WHERE " + HOW + " = ?";
            params = new Object[]{value};
        } else {
            sql = "SELECT * FROM " + TABLE_NAME_TXT + " WHERE " + HOW + " LIKE ?";
            params = new Object[]{"%" + value + "%"};
        }
        List<Map<String, String>> originalResult = queryWithParams(sql, params, HOW);

        // 隐藏敏感信息
        List<Map<String, String>> filteredResult = new ArrayList<>();
        for (Map<String, String> row : originalResult) {
            Map<String, String> filteredRow = new HashMap<>(row);
//            if (filteredRow.containsKey("TXT_id")) {
//                filteredRow.put("TXT_id", "***");
//            }
            filteredResult.add(filteredRow);
        }
        return filteredResult;
    }
}